<script setup>
import MyComponent from "@components/MyComponents/MyComponent.vue";
import { BigNumber } from "bignumber.js";
import FancyButton from "@components/MyComponents/FancyButton.vue";
import DefaultSlotComposition from "@components/MyComponents/DefaultSlotComposition.vue";
import FancyList from "@components/MyComponents/FancyList.vue";
import MouseTracker from "@components/MyComponents/MouseTracker.vue";
import InjectComposition from "@components/MyComponents/InjectComposition.vue";
import useMouse from "../../plugins/mouse.js";
import { useI18n } from '@/composables/useI18n';
import useFetch from '../../plugins/fetch.js'
import { hydrateOnVisible } from "vue";

const count = ref(0);
const increment = async () => {
  count.value++;
  await nextTick(() => {
    console.log(count.value);
  });
};

const state = reactive({
  count: 0
})

//与 reactive 对象不同的是，当 ref 作为响应式数组或原生集合类型 (如 Map) 中的元素被访问时，它不会被解包：
const books = reactive([ref('book1')]);
// console.log(books[0].value)
const map = reactive(new Map([
    ['count', ref(0)]
    ]));
// console.log(map.get('count').value)

//在模板渲染上下文中，只有顶级的 ref 属性才会被解包。
// 在下面的例子中，object 是顶级属性，但 object.id 不是：
const object = { id: ref(1)}
//为了解决这个问题，我们可以将 id 解构为一个顶级属性：
const { id } = object

const author = reactive({
  name: 'John Doe',
  books: [
    'Vue 2 - Advanced Guide',
    'Vue 3 - Basic Guide',
    'Vue 4 - The Mystery'
  ]
});
const publishBooksMessage = computed(() => {
  return author.books.length > 0 ? 'Yes' : 'No';
});

const x = ref(0);
const y = ref(0);
const Sum = computed(() => {
  const numX = isNaN(parseFloat(x.value)) ? 0 : x.value;
  const numY = isNaN(parseFloat(y.value)) ? 0 : y.value;
  return new BigNumber(numX).plus(numY).toString();
});

const list = ref( [
  {message : 'this is the first message!'},
  {message : 'this is the second message!'},
]);

const myObject = reactive({
  title: 'How to do lists in Vue',
  name: 'Jane Doe',
  publishedAt: '2016-04-10'
})

const message = ref('');
const messageText = ref('');
const remark = ref('');
const input = useTemplateRef('my-input');
const handClick = () => {
  messageText.value = message.value;
  input.value.focus();
};

const postFontSize = ref(1);
const increaseFontSize = (n) => {
  if ( postFontSize.value < 2 && n < 0 ) {
    postFontSize.value = 1;
  } else {
    postFontSize.value += n;
  }
};

const handChange = (val) => {
  postFontSize.value = val;
};

const url = ref('');

const handSubmit = (value) => {
  console.log('submit',  value);
};
const countModel = ref(0);
const myText = ref('hello,world!');

provide('message', 'hello,world!');

const location = ref('North Polo');
const updateLocation = () => {
  location.value = 'South Polo';
}
provide('location', {
  location,
  updateLocation
});


const AdminPage = defineAsyncComponent({
  loader: () => import('../MyComponents/AdminPage.vue'),
  hydrate: hydrateOnVisible({ rootMargin: '500px'}),//当滚动到距离视口500像素的位置时，组件将开始hydrate
});

const {a, b} = useMouse();





const baseUrl = 'https://jsonplaceholder.typicode.com/todos/'
const itemId = ref('1')
const fetch_url = computed(() => baseUrl + itemId.value)

const { data, error } = useFetch(fetch_url)

const retry = () => {
  itemId.value = 1;
}
// 只有当所需功能只能通过直接的 DOM 操作来实现时，才应该使用自定义指令。
const vHighlight = {
  mounted : (el) => {
    el.style.backgroundColor = 'yellow'
  },
}
//该指令比 autofocus 属性更有用，因为它不仅在页面加载时有效，而且在 Vue 动态插入元素时也有效！
const vFocus = {
  mounted : (el) => el.focus(),
}

const vExample = {
  mounted: (el, binding) => {
    if (binding.arg === 'style') {
      const styleObj = binding.value;
      console.log('styleObj', Object.entries(styleObj));
      for (const [key, val] of Object.entries(styleObj)) {
        if (typeof val === 'string') {
          el.style[key] = val;
        } else {
          console.warn(`Invalid value for style property "${key}":`, val);
        }
      }
    } else if (binding.arg === 'class') {
      const classList = binding.value;
      el.classList.add(...classList);
    } else if (binding.arg === 'text') {
      el.textContent = binding.value;
    } else {
      console.warn(`Invalid arg for v-example: "${binding.arg}"`);
    }
  },
}

const styleObject = ref({
  fontSize: '20px',
  color: 'red',
});



// const { t } = useI18n();
// console.log('t', t('greetings.hello'));

const i18n = inject('i18n');
console.log('i18n', i18n.greetings.hello);

watch( message, (newValue, oldValue) => {
      console.log('message', newValue, oldValue);
    }, {
      // immediate: true,
      deep: true,
    }
);

</script >

<template >
  <div style="width: 1000px;">
<!--    <p v-highlight>this is a test</p>-->
<!--    <AInput v-focus></AInput>-->
    <div v-example:style="styleObject" v-example:class="['info']" v-example:text="'测试文本'"></div>
    
<!--    <ASpace>-->
<!--      <AButton @click="count = 0">重置</AButton>-->
<!--      <AButton @click="increment" :type="count > 0 ? 'primary' : 'default'">点击{{ count }}次</AButton>-->
<!--      <AButton @click="() => state.count++">reactive点击 {{ state.count }} 次</AButton>-->
<!--      <AButton @click="() => books[0].value = 'book3'">books[0]点击 {{ books[0].value }}</AButton>-->
<!--      <AButton @click="() => id++">object.id点击 {{ id }}</AButton>-->
<!--    </ASpace>-->
<!--    -->
<!--    <p>Has published books:{{ publishBooksMessage }}</p>-->
<!--    -->
<!--    <AInputGroup>-->
<!--      <ARow :gutter="8">-->
<!--        <ACol><AInputNumber v-model:value="x" :controls="false"/></ACol>-->
<!--        <ACol><AButton shape="circle">+</AButton></ACol>-->
<!--        <ACol><AInputNumber v-model:value="y" :controls="false"/></ACol>-->
<!--        <ACol><AButton shape="circle">=</AButton></ACol>-->
<!--        <ACol><AButton>{{ Sum }}</AButton></ACol>-->
<!--      </ARow>-->
<!--    </AInputGroup>-->
    
<!--    <div >-->
<!--&lt;!&ndash;      //父组件的样式会透传给子组件 ，但是如果样式在父组件和子组件中都有，那么父组件的类样式会覆盖子组件的类样式。&ndash;&gt;-->
<!--      <MyComponent class="border-gray mt-10 mb-10" size="big"-->
<!--          @enlarge-text="increaseFontSize"-->
<!--          @change="handChange"-->
<!--          :font-size="postFontSize"-->
<!--          :author="myObject"-->
<!--          @submit="handSubmit"-->
<!--          v-model:value="countModel"-->
<!--          v-model:text.capitalize="myText"-->
<!--          @click="() => console.log('click1')"-->
<!--          id="my-id"-->
<!--      >-->
<!--        <template #title="{ title , message}">-->
<!--          <div :style="{fontSize: postFontSize + 'em'}">标题2</div>-->
<!--          <div>{{ title }}</div>-->
<!--          <div>{{ message }}</div>-->
<!--        </template>-->
<!--        <template #content>-->
<!--          <div>内容</div>-->
<!--        </template>-->
<!--        <template #footer>-->
<!--          <div>底部</div>-->
<!--        </template>-->
<!--      </MyComponent>-->
<!--    </div>-->
<!--    <div>-->
<!--      <FancyButton>-->
<!--        Click me！-->
<!--      </FancyButton>-->
<!--    </div>-->
<!--    <div class="mt-10">-->
<!--      <DefaultSlotComposition v-slot="{text, count}">-->
<!--        {{ text }}-->
<!--        {{ count }}-->
<!--      </DefaultSlotComposition>-->
<!--    </div>-->
    
<!--    <div class="mt-10">-->
<!--      <FancyList :api-url="url" :pre-page="10">-->
<!--        <template #item="{ body , username, likes}">-->
<!--          <div class="item">-->
<!--            <div>{{ body }}</div>-->
<!--            <div>{{ username }} | {{ likes }}</div>-->
<!--          </div>-->
<!--        </template>-->
<!--      </FancyList>-->
<!--    </div>-->
<!--    -->
<!--    <div>-->
<!--      <MouseTracker v-slot="{x, y}">-->
<!--        Mouse is At : ({{ x }}, {{ y }})-->
<!--      </MouseTracker>-->
<!--    </div>-->
<!--    -->
<!--    <div>-->
<!--      <InjectComposition></InjectComposition>-->
<!--    </div>-->
<!--    -->
<!--    <div>-->
<!--      <AdminPage></AdminPage>-->
<!--    </div>-->
    
<!--    <div class="mb-10">-->
<!--      <AList bordered >-->
<!--        <AListItem v-for="({message}, index) of list" :key="index">-->
<!--          <div>{{ index + 1 }}、{{message}}</div>-->
<!--        </AListItem>-->
<!--      </AList>-->
<!--      -->
<!--      <AList bordered class="mt-10">-->
<!--        <AListItem v-for="(value, key , index) of myObject" :key="index">-->
<!--          <div>{{ index + 1 }} - {{ key }} - {{ value }}</div>-->
<!--        </AListItem>-->
<!--      </AList>-->
<!--    </div>-->
    
<!--    <div class="mb-10">-->
<!--      <AInputGroup compact>-->
<!--        <AInput v-model:value="message" placeholder="Please input" style="width: calc(80% - 200px)" ref="my-input"/>-->
<!--        <AButton @click="handClick" type="primary">Button</AButton>-->
<!--      </AInputGroup>-->
<!--      <p class="mt-10">Message is :{{ messageText }}</p>-->
<!--    </div>-->
<!--    -->
<!--    <div class="mb-10">-->
<!--      <ATextarea v-model:value="remark" :rows="4" :maxlength="6" placeholder="请输入内容"></ATextarea>-->
<!--    </div>-->
    
<!--    <div>-->
<!--      Mouse position is at: {{ a }}, {{ b }}-->
<!--    </div>-->
<!--    -->
<!--    <div>-->
<!--      Load post id:-->
<!--      <AButton v-for="i in 5" @click="itemId = i">{{ i }}</AButton>-->
<!--      -->
<!--      <div v-if="error">-->
<!--        <p>Oops! Error encountered: {{ error.message }}</p>-->
<!--        <AButton @click="retry">Retry</AButton>-->
<!--      </div>-->
<!--      <div v-else-if="data">Data loaded: <pre>{{ data }}</pre></div>-->
<!--      <div v-else>Loading...</div>-->
<!--    </div>-->
  </div>
  
</template >

<style scoped >
.border-gray {
  border: 1px solid gray;
}
.margin-10 {
  margin: 10px;
}
.mt-10 {
  margin-top: 10px;
}
.mb-10 {
  margin-bottom: 10px;
}
.info {
  border: 1px solid blue;
  border-radius: 5px;
  padding: 20px;
}
</style >